package dbinit;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import core.address.model.continent.Continent;
import core.util.HibernateCoreUtil;

public class InitContinent 
{
	public static Continent getContinentByName(String name)
	{
		Continent c = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			c = (Continent)session.createCriteria(Continent.class).add(Restrictions.eq("name", name)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return c ;
	}
	public static Continent getContinentByUuid(Long uuid)
	{
		Continent c = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				c = (Continent) session.get(Continent.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return c ;
	}
	public static Long doinit(String name)
	{
		Continent continent = getContinentByName(name);
		Long uuid = null;
		if(continent == null)
		{
			Transaction transaction = null;
			Session session = HibernateCoreUtil.getSessionFactory().openSession();
			continent = new Continent();
			continent.setName(name);
			try
			{
				transaction = session.beginTransaction();
				uuid = (Long)session.save(continent);
				transaction.commit();
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
			finally
			{
				session.close();
			}
		}
		else
		{
			uuid = continent.getUuid();
		}
		return uuid ;
	}
}
